package it.giuseppetrisciuoglio.lyrics.parser;

import it.giuseppetrisciuoglio.lyrics.exception.LyricsNotFoundException;

import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

public class MetroLyricsTestoParser extends AbstractTestoParser {

	//http://www.metrolyrics.com/albachiara-lyrics-vasco-rossi.html
	private static String SITE = "http://www.metrolyrics.com/";
	private static String BLANK_CHAR = "-";
	
	@Override
	public String getTesto(String httpResponse) throws LyricsNotFoundException, ParserException {
		NodeFilter filter =  new AndFilter(
		        new TagNameFilter("div"),
		        new HasAttributeFilter("class", "lyrics-body"));
		return super.getTestoParse(httpResponse, filter);
	}
	
	@Override
	protected String getTestoParse(String httpResponse, NodeFilter filter) throws ParserException, LyricsNotFoundException {
		Parser parser = new Parser(httpResponse);
		NodeList nodeList = parser.parse(filter);
		String responseTesto = nodeList.toHtml().trim();
		if (responseTesto == null || responseTesto.isEmpty()){
			log.error("getTestoParse(): artista or titolo is null, returning.");
			throw new LyricsNotFoundException();
		}
		return responseTesto.trim();
	}
	
	
	@Override
	public String getURL(String artista, String titolo) throws IllegalArgumentException {
		super.validArtistaAndTitolo(artista, titolo);
		return SITE.concat("/")
				.concat(cleanTitolo(titolo.trim().toLowerCase().replaceAll(" ", BLANK_CHAR)))
				.concat("-")
				.concat(cleanArtista(artista.trim().toLowerCase().replaceAll(" ", BLANK_CHAR)));
	}

	@Override
	protected String cleanTitolo(String titolo) {
		titolo = super.cleanTitolo(titolo);
		return titolo.replace('\'', ' ')
				.replace('.', ' ')
				.replace('(', ' ')
				.replace(')', ' ')
				.replace(',', ' ')
				.replace('"', ' ')
				.replace(':', ' ')
				.replaceAll(" ", "");
	}

	@Override
	protected String cleanArtista(String artista) {
		artista = super.cleanArtista(artista);
		return artista.replace('\'', ' ')
				.replace('.', ' ')
				.replace('(', ' ')
				.replace(')', ' ')
				.replace(',', ' ')
				.replace('"', ' ')
				.replace(':', ' ')
				.replaceAll(" ", "");
	}

}
